package cn.abcode.test.springbootsecurity.demo.controller;

import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
@RequestMapping("/kaptcha")
public class VerifyCodeController {

    @Autowired
    private Producer producer;

    @GetMapping("/getCode")
    public void getVerifyCode(HttpServletResponse response, HttpSession session) throws IOException {
        response.setContentType("image/jpeq");
        String text = producer.createText();
        session.setAttribute("verify_code", text);
        BufferedImage image = producer.createImage(text);

        try {
            ServletOutputStream out = response.getOutputStream();
            ImageIO.write(image, "jpg", out);
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    @GetMapping("/getCodeStr")
    public String getCodeStr(HttpServletResponse response, HttpSession session) throws IOException {

        String text = producer.createText();
        session.setAttribute("verify_code", text);

        return text;
    }
}
